//
//  ImageUpload.swift
//  ReactNativeIOS
//
//  Created by 陆文宇 on 2017/11/3.
//  Copyright © 2017年 chenliang. All rights reserved.
//

import UIKit

class ImageUpload: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate, MLImageCropDelegate, YYImagePickerViewControllerDelegate {
    
    var doneClosure: ((String) -> Void)!
    var type: String!
    var size: CGSize!
    var token: String!
    var filetag: String!
    var images: [UIImage]?
    
    var num: Int!
    
    init(type: String, size_w: CGFloat, size_h: CGFloat, token: String, filetag: String, doneClosure: @escaping (String) -> Void) {
        self.type = type
        self.size = CGSize(width: size_w, height: size_h)
        self.token = token
        self.filetag = filetag
        self.doneClosure = doneClosure
        
        super.init()
    }
    
    init(num: Int, token: String, filetag: String, doneClosure: @escaping (String) -> Void) {
        self.num = num
        self.token = token
        self.filetag = filetag
        self.doneClosure = doneClosure
        
        super.init()
    }
    
    func performOne() {
        let picker = UIImagePickerController()
        picker.delegate = self
        picker.allowsEditing = false
        if type == "takephoto" {
            if !UIImagePickerController.isSourceTypeAvailable(.camera) {
                SVProgressHUD.showError(with: "相机不支持")
                return
            }
            picker.sourceType = .camera
        } else if type == "choose" {
            picker.sourceType = .photoLibrary
        }
        YYRouter.currentVC.present(picker, animated: true, completion: nil)
    }
    
    func performDuo() {
        let picker = YYImagePickerViewController()
        picker.yy_delegate = self
        picker.yy_maxPickCount = num
        YYRouter.currentVC.present(picker, animated: true, completion: nil)
    }
    
    func resume() {
        guard images != nil && !images!.isEmpty else {
            return
        }
        
        var params = [String: Data]()
        images?.forEach({ (image) in
            params["\(filetag!)/\(UIImage.yy_createName())"] = image.yy_JPEGData()
        })
        SVProgressHUD.showStatus("正在上传...")
        YYQiniu.multipleUpload(data: params, token: token, success: { (filenames) in
            SVProgressHUD.dismiss()
            self.doneClosure(filenames.joined(separator: ";"))
        }) {
            SVProgressHUD.dismiss()
            self.doneClosure("")
            SVProgressHUD.showError(with: "上传失败")
        }
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        picker.dismiss(animated: true, completion: nil)
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        images = [image]
        
        if size.width != 0 && size.height != 0 {
            let crop = MLImageCrop()
            crop.delegate = self
            crop.image = image
            crop.ratioOfWidthAndHeight = size.width / size.height
            crop.show(withAnimation: false)
        } else {
            resume()
        }
    }
    
    func cropImage(_ cropImage: UIImage!, forOriginalImage originalImage: UIImage!) {
        images = [cropImage]
        resume()
    }
    
    func yy_imagePickerViewController(_ controller: YYImagePickerViewController, choosedPhotos photos: Array<YYPhotoModel>) {
        controller.dismiss(animated: true, completion: nil)
        
        images = photos.map({ (photo) -> UIImage in
            return photo.originalImage
        })
        resume()
    }
}
